package com.easylinkin.sm.context;

import com.easylinkin.sm.entity.Customer;
import com.easylinkin.sm.entity.Department;
import com.easylinkin.sm.service.CustomerService;

import static com.easylinkin.sm.constant.CustomerConstant.Caches.ACTIVE_CUSTOMER;
import static com.easylinkin.sm.constant.CustomerConstant.Caches.CUSTOMER;

import java.util.Objects;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import site.morn.bean.annotation.Target;
import site.morn.cache.CacheGroup;
import site.morn.framework.context.AccountContext;
import site.morn.framework.context.function.ActiveProducer;

/**
 * 获取当前客户
 *
 * @author TianGanLin
 * @since 1.0.0, 2019/8/27
 */
@Component
@Target(Customer.class)
public class SmCustomerContextProducer implements ActiveProducer<Customer> {

  @Resource
  private CustomerService customerService;

  @Override
  public Customer getActive() {
    String username = AccountContext.currentUsername();
    Department department = AccountContext.activeDepartment();
    CacheGroup cacheGroup = AccountContext.cacheGroup();
    return cacheGroup.get(ACTIVE_CUSTOMER, username, () -> getByDepartment(department));
  }

  @Override
  public Customer getCurrent() {
    String username = AccountContext.currentUsername();
    Department department = AccountContext.currentDepartment();
    CacheGroup cacheGroup = AccountContext.cacheGroup();
    return cacheGroup.get(CUSTOMER, username, () -> getByDepartment(department));
  }

  /**
   * 根据机构获取客户
   *
   * @param department 组织机构
   * @return 客户
   */
  private Customer getByDepartment(Department department) {
    if (Objects.isNull(department)) {
      return null;
    }
    return customerService.get(department.getCustomerId());
  }
}
